package com.luoying.itew.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.luoying.itew.R;
import com.luoying.itew.adapter.AddressAdapter;
import com.luoying.itew.bean.AddressOnItemClickListener;
import com.luoying.itew.util.LogUtils;
import com.luoying.itew.util.ZXWUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Administrator on 2018/5/25.
 * time 2018-5-10
 * author zm
 */
@RuntimePermissions
public class SignInActivity extends BaseActivity implements
        PoiSearch.OnPoiSearchListener,AddressOnItemClickListener {
    final int REQUESTCODE_GPS =1000;
    private static final String TAG = "SignInActivity";
    public static final String GOING = "address";

    @BindView(R.id.toolbar_sign)
    Toolbar toolbarSign;
    @BindView(R.id.rec_sign)
    RecyclerView recSign;
    @BindView(R.id.rl_sign_next)
    Button rlSignSubmit;
    @BindView(R.id.address_map_view)
    MapView mMapView;


    public static Activity mFinish;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption;
    //搜索功能
    public PoiSearch.Query query;
    private PoiSearch poiSearch;
    private List<String> poiList = new ArrayList();
    private AddressAdapter addressAdapter;
    public String signAddress;

    private Dialog confirmDialog;
    /**
     * 地图控制类
     */
    private AMap aMap;

    @Override
    public int getLayoutResId() {
        return R.layout.sign_activity;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mMapView.onCreate(savedInstanceState);
        if(aMap==null){
            aMap = mMapView.getMap();
        }
        //地图类型
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);
    }

    @Override
    protected void init() {
        super.init();
        mFinish = this;
        recSign.setLayoutManager(new LinearLayoutManager(this));
        addressAdapter = new AddressAdapter(this, poiList);
        addressAdapter.setOnItemClickListener(this);
        recSign.setAdapter(addressAdapter);
        setMap();
    }

    private void setMap() {
        //定位初始化
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(new AMapLocationListenerImpl());
        mLocationOption = new AMapLocationClientOption();
        //设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        SignInActivityPermissionsDispatcher.needsPermissionWithPermissionCheck(this);
    }
    @Override
    protected void setSystemColor() {
        super.setSystemColor();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_sign);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //点击back键finish当前activity
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    @OnClick(R.id.rl_sign_next)
    public void onViewClicked() {
        rlSignSubmit.setEnabled(false);
        if(TextUtils.isEmpty(signAddress)){
            rlSignSubmit.setEnabled(true);
            Toast.makeText(this,"定位失败",Toast.LENGTH_LONG).show();
        } else {
            Intent intent = new Intent(this, SubmitLogActivity.class);
            intent.putExtra(GOING, signAddress);
            startActivity(intent);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                poiList.clear();
                poiList.add(aMapLocation.getAddress());
                signAddress = aMapLocation.getAddress();
                LogUtils.d("定位成功开始搜索");
                stareSerache(aMapLocation);
                darwLocation(aMapLocation);
            }else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                LogUtils.e("AmapError","location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                if(loadDialog.isShowing()){
                    loadDialog.dismiss();
                }
                Toast.makeText(this,"获取定位失败",Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 开始搜索周边POI信息
     * @param aMapLocation
     */
    public void stareSerache(AMapLocation aMapLocation){
        String citycode = aMapLocation.getCityCode();
        //190000是POI类型，由高德地图提供
        query = new PoiSearch.Query("","190000",citycode);
        query.setPageSize(10);
        query.setPageNum(0);
        poiSearch = new PoiSearch(this.getApplicationContext(), query);
        poiSearch.setOnPoiSearchListener(this);
        LatLonPoint lp = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        // 设置搜索区域为以lp点为圆心，其周围5000米范围
        poiSearch.setBound(new PoiSearch.SearchBound(lp, 1000, true));//
        //开始搜索®®
        poiSearch.searchPOIAsyn();
    }


    /**
     * 绘制自身所在位置信息
     * @param aMapLocation
     */
    public void darwLocation(AMapLocation aMapLocation){
        LatLng latLng = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions()
                .position(latLng)
                .draggable(false);
        aMap.addMarker(markerOptions);
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,12));
    }

    /**
     * 高地图搜索回调
     * @param poiResult
     * @param code
     */
    @Override
    public void onPoiSearched(PoiResult poiResult, int code) {
        LogUtils.e("onPoiSearched", "code:" + code);
        if(code==AMapException.CODE_AMAP_SUCCESS){
            for (PoiItem poiItem : poiResult.getPois()) {
                String addres = poiItem.getSnippet() + poiItem.getTitle();
                poiList.add(addres);
            }
            addressAdapter.notifyDataSetChanged();
        }
        if(loadDialog.isShowing()){
            loadDialog.dismiss();
        }
    }

    /**
     * 高地图搜索回调
     * @param poiItem
     * @param code
     */
    @Override
    public void onPoiItemSearched(PoiItem poiItem, int code) {
    }

    /**
     * 列表点击事件
     * @param address
     */
    @Override
    public void onItemClick(String address) {
        signAddress = address;
    }


    @Override
    protected void onResume() {
        super.onResume();
        rlSignSubmit.setEnabled(true);
        mMapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mFinish = null;
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION})
    void needsPermission() {
        //大于8.0需要开启GPS定位，才能获取定位信息
       if(Build.VERSION.SDK_INT>Build.VERSION_CODES.O){
           boolean locationEnabled = ZXWUtils.isLocationEnabled(this);
           if (!locationEnabled){
               showToastDialog();
           } else {
               startLoaction();
           }
       } else {
           startLoaction();
       }
    }

    /**
     * 弹出Dialog去确认是否退出
     */
    private void showToastDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_confirm, null);
        confirmDialog = new Dialog(this, R.style.ConfirmFrameWindowStyle);
        confirmDialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        Window window = confirmDialog.getWindow();

        WindowManager.LayoutParams wl = window.getAttributes();
        wl.gravity = Gravity.CENTER;
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width =(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,269, getResources().getDisplayMetrics());
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;//
        confirmDialog.onWindowAttributesChanged(wl);
        confirmDialog.setCanceledOnTouchOutside(false);
        confirmDialog.show();

        RelativeLayout cancel = (RelativeLayout) view.findViewById(R.id.rl_dialog_wallet_cancel);
        RelativeLayout go = (RelativeLayout) view.findViewById(R.id.rl_dialog_wallet_go);
        TextView right = (TextView) view.findViewById(R.id.tv_wallet_go);
        TextView tvCancel = (TextView) view.findViewById(R.id.tv_dialog_setting_cancel);
        TextView title = (TextView) view.findViewById(R.id.tv_wallet_text);
        title.setText("检测到您没有开启定位服务，会导致定位功能无法使用，是否开启？");
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmDialog.dismiss();
            }
        });

        go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //请求打开GPS
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, REQUESTCODE_GPS);
                confirmDialog.dismiss();
            }
        });

    }

    /**
     * 开始定位
     */
    private void startLoaction(){
        mLocationClient.setLocationOption(mLocationOption);
        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        mLocationClient.stopLocation();
        //开始定位
        mLocationClient.startLocation();
        loadDialog.show();
    }


    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,})
    void neverAskPermission(){
        Toast.makeText(this,"无定位授权,无法定位",Toast.LENGTH_LONG).show();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION})
    void permissionDenied(){
        Toast.makeText(this,"无定位授权,无法定位",Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUESTCODE_GPS){
            boolean locationEnabled = ZXWUtils.isLocationEnabled(this);
            if (!locationEnabled){
                showToastDialog();
            } else {
                startLoaction();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SignInActivityPermissionsDispatcher.onRequestPermissionsResult(this,requestCode,grantResults);

    }

}
